package cn.clouds234.jdkfile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CreateFileWithDirsLegacy {
    public static void main(String[] args) {
        // 定义文件路径（包含多级目录）
        String filePath = "F:/data/logs/2023/10/app.log";
 
        try {
            // 1. 创建父目录
            File parentDir = new File(filePath).getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                boolean dirsCreated = parentDir.mkdirs(); // 递归创建目录
                if (!dirsCreated) {
                    throw new IOException("无法创建目录: " + parentDir);
                }
            }
 
            // 2. 创建文件并写入内容
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write("This is a test log.\n");
                System.out.println("文件创建成功: " + new File(filePath).getAbsolutePath());
            }
        } catch (IOException e) {
            System.err.println("创建文件失败: " + e.getMessage());
        }
    }
}